package cc.linker.steplink.crm.merchanth5.service.coupon;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.coupon.CouponRequest;
import cc.linker.steplink.crm.commons.domain.WxUser;
import cc.linker.steplink.crm.commons.utils.CalendarUtils;
import cc.linker.steplink.crm.commons.yzj.YzjRequest;
import cc.linker.steplink.crm.merchanth5.dao.coupon.CouponH5Dao;
import cc.linker.steplink.crm.merchanth5.pojo.CheckMerchantOrderPo;
import cc.linker.steplink.crm.merchanth5.pojo.MallGoodsPo;
import cc.linker.steplink.crm.merchanth5.pojo.ShoppingCartGoodsPo;
import cc.linker.steplink.crm.merchanth5.pojo.coupon.*;
import cc.linker.steplink.crm.merchanth5.service.redis.CouponCacheService;
import cc.linker.steplink.crm.merchanth5.service.redis.CustomerCacheService;
import cc.linker.steplink.crm.merchanth5.service.redis.MerchantService;
import cc.linker.steplink.crm.response.GlobalException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * @Author: CKQ
 * @DateTime: 2020/8/20 13:32
 * @Description: TODO
 */
@Slf4j
@Service
public class CouponH5Service {
    @Autowired
    private CouponRequest couponRequest;
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private CouponH5Dao couponH5Dao;
    @Autowired
    private YzjRequest yzjRequest;
    @Autowired
    private CouponCacheService couponCacheService;

    @Autowired
    private CustomerCacheService customerCacheService;

    /**
     * @Description：领取优惠券
     * @DateTime：2020/8/20 13:37
     * @Params：
     * @Return：
     */
    public Object receiveConsumption(Map<String, Object> receiveParam, CouponCustomerInfo couponCustomerInfo, Boolean isActivity) {
        if (receiveParam == null) {
            throw GlobalException.build("请选择需要领取的卡券");
        }
        if (!receiveParam.containsKey("couponList") || receiveParam.get("couponList") == null) {
            throw GlobalException.build("请选择需要领取的卡券");
        }
        List<Map> coupons = new ArrayList<>();
        List<Map> couponList = (List<Map>) receiveParam.get("couponList");
        if (couponList.size() == 0) {
            throw GlobalException.build("请选择需要领取的卡券");
        }
        String couponIds = "";
        for (Map map : couponList) {
            couponIds += map.get("couponId").toString() + ",";
        }
        couponIds = couponIds.substring(0, couponIds.length() - 1);
        Map<String, Object> countParams = new HashMap<>();
        countParams.put("couponIds", couponIds);
        countParams.put("type", 0);
        Object customerCouponCountObj = couponRequest.doRequest("customer-coupons-count", countParams, couponCustomerInfo);
        Map<String, Object> customerCountObj = (Map) customerCouponCountObj;
        List<Map<String, Object>> couponCountList = (List<Map<String, Object>>) customerCountObj.get("couponCountList");
        boolean isReceive = true;
        for (Map map : couponList) {
            String couponId = map.get("couponId").toString();
            Map<String, Object> p = new HashMap<>();
            CouponTacticsPo couponTacticsPo = this.couponH5Dao.getCouponGoodsData(couponId);
            if (couponTacticsPo != null) {
                // region 判断是否超过购买限制
                for (Map<String, Object> countMap : couponCountList) {
                    //如果用户领取的记录里优惠券数量大于等于限制则不能领取
                    if (countMap.get("couponId").toString().equals(couponId)
                            && couponTacticsPo.getCustomerCouponNum() != -1
                            && Integer.valueOf(countMap.get("count").toString()) >= couponTacticsPo.getCustomerCouponNum()) {
                        isReceive = false;
                        if (!isActivity) {
                            throw GlobalException.build("不要贪心，每人最多能领取" + couponTacticsPo.getCustomerCouponNum() + "张哦~");
                        }
                    }
                }
                //endregion
                //region 判断是否新用户老用户限制
                if (map.containsKey("createCustomerId") && !StringUtils.isEmpty(map.get("createCustomerId"))) {
                    Integer orderCount = 0;
                    if (couponTacticsPo.getCustomerType() == 1 || couponTacticsPo.getCustomerType() == 2) {
                        orderCount = this.couponH5Dao.getCustomerStoreOrderCount(couponCustomerInfo.getCustomerId(), map.get("createCustomerId").toString());
                    }
                    switch (couponTacticsPo.getCustomerType()) {
                        //新用户
                        case 1:
                            if (orderCount != 0) {
                                isReceive = false;
                                if (!isActivity) {
                                    throw GlobalException.build("您已经是老用户了，无法领取哦~");
                                }
                            }
                            break;
                        case 2:
                            if (orderCount == 0) {
                                isReceive = false;
                                if (!isActivity) {
                                    throw GlobalException.build("您还是新用户，无法领取哦~");
                                }
                            }
                            break;
                        case 3:
                            //用户分群
                            if (!StringUtils.isEmpty(couponTacticsPo.getGroupId())) {
                                Integer isExit = this.couponH5Dao.isCustomerExitGroup(couponCustomerInfo.getCustomerId(), couponTacticsPo.getGroupId());
                                if (isExit == 0) {
                                    isReceive = false;
                                    if (!isActivity) {
                                        throw GlobalException.build("您不符合领取条件");
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
                //endregion
                if (isReceive) {
                    p.put("couponId", map.get("couponId"));
                    p.put("publishId", map.containsKey("publishId") ? map.get("publishId") : "");
                    coupons.add(p);
                }
            }
        }
        if (coupons.size() > 0) {
            Map<String, Object> params = new HashMap<>();
            params.put("couponList", coupons);
            params.put("isActivity", isActivity);
            return couponRequest.doRequest("customer-coupon-receive", params, couponCustomerInfo);
        }
        Map<String,Object> result = new HashMap<>();
        result.put("consumptionId","");
        return result;
    }

    /**
     * @Description：获取用户的优惠券列表
     * @DateTime：2020/8/20 18:52
     * @Params：
     * @Return：
     */
    public Object getCustomerCouponPageList(Map<String, Object> params, CouponCustomerInfo couponCustomerInfo) {
        params.put("pageSize", 1000);
        Object result = couponRequest.doRequest("customer-coupon-page-list", params, couponCustomerInfo);
        Map<String, Object> info = (Map) result;
        List<CustomerCouponVo> customerCouponVoList = JSON.parseArray(info.get("list").toString(), CustomerCouponVo.class);
        if (!StringUtils.isEmpty(couponCustomerInfo.getSourceUserId())) {
            Map<String, Object> memberCouponResult = this.yzjRequest.getMemberCouponList(couponCustomerInfo.getSourceUserId());
            List<CustomerCouponVo> yzjCouponList = this.yzjCouponToCrmCoupon(memberCouponResult, (Integer) params.get("status"),couponCustomerInfo, Integer.parseInt(params.get("type").toString()));
            if (yzjCouponList != null && yzjCouponList.size() > 0) {
                customerCouponVoList.addAll(yzjCouponList);
            }
        }
        if (customerCouponVoList != null && customerCouponVoList.size() > 0) {
            for (CustomerCouponVo customerCouponVo : customerCouponVoList) {
                Map<String, Object> storeMap = this.customerCacheService.getCustomerCacheStoreInfo(couponCustomerInfo.getOrgId(),
                        customerCouponVo.getCreateCustomerId(),
                        customerCouponVo.getCreateCustomerId().equals(couponCustomerInfo.getOrgId())?"1":"2");
                if (storeMap != null && !StringUtils.isEmpty(storeMap.get("storeName"))) {
                    customerCouponVo.setStoreName(storeMap.get("storeName") != null ? storeMap.get("storeName").toString() : "");
                    customerCouponVo.setStoreLogo(storeMap.get("storeLogo") != null ? storeMap.get("storeLogo").toString() : "");
                } else {
                    customerCouponVo.setCreateCustomerId("");
                }
            }
            //按领取日期倒叙排序
            customerCouponVoList = customerCouponVoList.stream().sorted(Comparator.comparing(CustomerCouponVo::getCreateTime).reversed()).collect(Collectors.toList());
        }
        List<StoreInfoVo> storeList = new ArrayList<>();
        for (CustomerCouponVo customerCouponVo : customerCouponVoList) {
            if (storeList.stream().filter(item -> item.getStoreId().equals(customerCouponVo.getCreateCustomerId())).count() == 0) {
                storeList.add(StoreInfoVo.builder()
                        .storeId(customerCouponVo.getCreateCustomerId())
                        .storeName(customerCouponVo.getStoreName())
                        .storeLogo(customerCouponVo.getStoreLogo())
                        .build());
            }
        }
        //遍历店铺列表
        for (StoreInfoVo storeInfoVo : storeList) {
            storeInfoVo.setCustomerCouponVoList(customerCouponVoList.stream()
                    .filter(item -> item.getCreateCustomerId().equals(storeInfoVo.getStoreId()))
                    .collect(Collectors.toList()));
        }
        return storeList;
    }

    /**
    * @Description：解析雅智捷的优惠券到我们crm的格式
    * @DateTime：2020/12/4 11:00
    * @Params：
    * @Return：
    */
    private List<CustomerCouponVo> yzjCouponToCrmCoupon(Map<String, Object> memberCouponResult,Integer paramStatus, CouponCustomerInfo couponCustomerInfo,Integer type) {
        if (memberCouponResult == null) {
            return null;
        }
        List<CustomerCouponVo> customerCouponVoList = new ArrayList<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        if (memberCouponResult != null && memberCouponResult.containsKey("total_count") && memberCouponResult.get("total_count") != null && (int) memberCouponResult.get("total_count") > 0) {
            List<Map<String, Object>> couponList = (List<Map<String, Object>>) memberCouponResult.get("results");
            for (Map<String, Object> stringObjectMap : couponList) {
                Integer status = (Integer) stringObjectMap.get("status");
                //region 组装雅智捷的数据为我们的实体类
                try {
                    String effDate = formatter.format(df.parse(stringObjectMap.get("effective_date").toString()));
                    String exDate = formatter.format(df.parse(stringObjectMap.get("expired_date").toString()));
                    Map<String, Object> couponInfoMap = (Map<String, Object>) stringObjectMap.get("coupon_info");
                    String useDesc = "";
                    if (couponInfoMap.get("term_condition") != null) {
                        useDesc = this.getUseDesc((String) couponInfoMap.get("term_condition"));
                    }

                    String condition = "";
                    BigDecimal minPrice = ((BigDecimal) couponInfoMap.get("minimum_purchase_condition")).setScale(2, BigDecimal.ROUND_HALF_UP);
                    BigDecimal zeroPrice = new BigDecimal(0);
                    BigDecimal price = ((BigDecimal) stringObjectMap.get("coupon_value")).setScale(2, BigDecimal.ROUND_HALF_UP);
                    if (stringObjectMap.get("coupon_type_code").toString().equals("cash")) {
                        if (minPrice.compareTo(zeroPrice) == 1) {
                            condition = "满" + minPrice + "减" + price + "元";
                        } else {
                            condition = "无门槛减" + price + "元";
                        }
                    } else {
                        price = price.multiply(new BigDecimal("10"));
                        if (minPrice.compareTo(zeroPrice) == 1) {
                            condition = "满" + minPrice + "享" + price + "折";
                        } else {
                            condition = "无门槛享" + price + "折";
                        }
                    }
                    String createCustomerId = "";

                    if (couponInfoMap.containsKey("stores") && couponInfoMap.get("stores") != null) {
                        List<Map<String, Object>> stores = (List) couponInfoMap.get("stores");
                        if (stores.size() > 0) {
                            createCustomerId = stores.get(0).containsKey("store_code") ? stores.get(0).get("store_code").toString() : "";
                        }
                    }
                    CustomerCouponVo customerCouponVo = CustomerCouponVo.builder()
                            .couponId(stringObjectMap.get("coupon_code").toString())
                            .consumptionId(stringObjectMap.get("coupon_serial_no").toString())
                            .name(stringObjectMap.get("coupon_name").toString())
                            .type(stringObjectMap.get("coupon_type_code").toString().equals("cash") ? 0 : 1)
                            .discountPriceStr(price.toString())
                            .discountNumStr(price.toString())
                            .minUsePriceStr(minPrice.toString())
                            .usableStartTime(effDate)
                            .usableEndTime(exDate)
                            .status(status.equals(1) ? 0 : (status.equals(3) ? 2 : 1))
                            .createCustomerId(createCustomerId)
                            .createTime(formatter.format(df.parse(stringObjectMap.get("create_date").toString())))
                            .isYzjCoupon(1)
                            .useScene(1)
                            .condition(condition)
                            .conditionUrl(couponInfoMap != null ? couponInfoMap.get("term_condition").toString() : "")
                            .useDesc(useDesc)
                            .memberCode(couponCustomerInfo.getSourceUserId())
                            .customerId(couponCustomerInfo.getCustomerId())
                            .build();
                    customerCouponVoList.add(customerCouponVo);
                } catch (Exception ex) {
                    LOGGER.error("解析雅智捷优惠券数据失败" + JSON.toJSONString(stringObjectMap));
                }
                //endregion
            }
        }
        //把雅智捷的券缓存到缓存中
        this.couponCacheService.setYzjCouponsToCache(customerCouponVoList);

        List<CustomerCouponVo> reCustomerCouponVoList = new ArrayList<>();
        for (CustomerCouponVo customerCouponVo : customerCouponVoList) {
            if (((paramStatus.equals(0) && customerCouponVo.getStatus().equals(0))
                    || ((paramStatus.equals(-2) && ((customerCouponVo.getStatus().equals(1) || customerCouponVo.getStatus().equals(2)))))) && (
                    type.equals(-1) || type.equals(customerCouponVo.getType())
            )) {
                reCustomerCouponVoList.add(customerCouponVo);
            }

        }
        return reCustomerCouponVoList;
    }

    private String getUseDesc(String url){
        try {
            URL urlContent = new URL(url);
            HttpURLConnection con = (HttpURLConnection) urlContent.openConnection();
            con.setRequestMethod("GET");
            con.setConnectTimeout(4 * 1000);
            con.setInstanceFollowRedirects(false);
            InputStream inputStream = con.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            String sCurrentLine = "";
            String sTotalString = "";
            while ((sCurrentLine = reader.readLine()) != null) {
                sTotalString += sCurrentLine;
            }
            return sTotalString;
        }catch (Exception ex){
            LOGGER.error("获取条件数据失败",ex);
            return "";
        }
    }

    /**
     * @Description：获取优惠券详情
     * @DateTime：2020/9/8 10:30
     * @Params：
     * @Return：
     */
    public Map<String, Object> getCouponDetail(Map<String, Object> params, CouponCustomerInfo couponCustomerInfo) {
        Object result = couponRequest.doRequest("customer-coupon-info", params, couponCustomerInfo);
        Map<String, Object> info = (Map) result;
        if (info != null && info.size()>0) {
            Map<String, Object> storeMap = this.customerCacheService.getCustomerCacheStoreInfo(couponCustomerInfo.getOrgId(),
                    info.get("createCustomerId").toString(),
                    info.get("createCustomerId").toString().equals(couponCustomerInfo.getOrgId())?"1":"2");
            info.put("storeName", storeMap.get("storeName").toString());
            info.put("storeLogo", storeMap.get("storeLogo").toString());
            Integer goodsType = merchantService.getCouponGoodsType(info.get("couponId").toString());
            info.put("goodsType",goodsType);
        }
        return info;
    }


    /**
     * @Description：获取优惠券详情
     * @DateTime：2020/8/21 8:34
     * @Params：
     * @Return：
     */
    public Map<String, Object> getCouponGoodsData(Map<String, Object> param, CouponCustomerInfo couponCustomerInfo) {
        Map<String, Object> res = (Map) couponRequest.doRequest("coupon-detail", param, couponCustomerInfo);
        if (null == res || res.isEmpty()) {
            throw GlobalException.notFound();
        }
        CouponTacticsPo couponGoodsData = couponH5Dao.getCouponGoodsData(param.get("couponId").toString());
        if (res != null) {
            res.put("goodsType", couponGoodsData == null ? 0 : couponGoodsData.getGoodsType());
            res.put("customerCouponNum", couponGoodsData == null ? 0 : couponGoodsData.getCustomerCouponNum());
            res.put("customerType", couponGoodsData == null ? 0 : couponGoodsData.getCustomerType());
            Map<String, Object> storeMap = this.customerCacheService.getCustomerCacheStoreInfo(couponCustomerInfo.getOrgId(),
                    res.get("createCustomerId").toString(),
                    res.get("createCustomerId").toString().equals(couponCustomerInfo.getOrgId()) ? "1" : "2");
            if (storeMap != null) {
                res.put("storeName", storeMap.containsKey("storeName") ? (String) storeMap.get("storeName") : "");
                res.put("storeLogo", storeMap.containsKey("storeLogo") ? storeMap.get("storeLogo") : "");
            }
        }
        return res;
    }

    /**
    * @Description：获取用户的优惠券数量
    * @DateTime：2020/12/7 13:58
    * @Params：
    * @Return：
    */
    public Map<String,Object> getCustomerCouponCount(Map<String,Object> params, CouponCustomerInfo couponCustomerInfo) {
        Object result = couponRequest.doRequest(params.get("active").toString(), params, couponCustomerInfo);
        Map<String, Object> info = (Map) result;
        Map<String, Object> memberCouponResult = this.yzjRequest.getMemberCouponList(couponCustomerInfo.getSourceUserId());
        if (memberCouponResult != null) {
            List<CustomerCouponVo> yzjCouponList = this.yzjCouponToCrmCoupon(memberCouponResult, 0,couponCustomerInfo,-1);
            if (yzjCouponList != null && yzjCouponList.size() > 0) {
                int count = 0;
                for (CustomerCouponVo customerCouponVo : yzjCouponList) {
                    Map<String, Object> storeMap = this.customerCacheService.getCustomerCacheStoreInfo(couponCustomerInfo.getOrgId(),
                            customerCouponVo.getCreateCustomerId(),
                            customerCouponVo.getCreateCustomerId().equals(couponCustomerInfo.getOrgId()) ? "1" : "2");
                    if(storeMap!=null && !StringUtils.isEmpty(storeMap.get("storeName")) ){
                        count++;
                    }
                }
                info.put("count", (Integer) info.get("count") + count);
            }
        }
        return info;
    }


    /**
     * @Description：优惠券状态更改
     * @DateTime：2020/8/21 8:34
     * @Params：consumptionId 核销券ID
     * @Params：orderSn 订单ID
     * @Params：payMoney 支付金额
     * @Params：payGoodsNum 订单商品数量
     * @Params：discountsMoney 优惠金额
     * @Params：status 0使用优惠券  1回滚优惠券
     * @Return：
     */
    @Async
    public void useConsumption(String consumptionId, Integer payMoney, String orderSn, Integer payGoodsNum, Integer discountsMoney, Integer status, CouponCustomerInfo couponCustomerInfo) {
        Map param = new HashMap();
        param.put("consumptionId", consumptionId);
        param.put("payMoney", payMoney);
        param.put("orderSn", orderSn);
        param.put("payGoodsNum", payGoodsNum);
        param.put("discountsMoney", discountsMoney);
        param.put("status", status);
        LOGGER.info("使用优惠券参数===[{}]", param);
        couponRequest.doRequest("customer-coupon-use", param, couponCustomerInfo);
    }


    /**
     * @Description 通过商品获取可领取的优惠券列表
     * @DateTime：2020/8/21 13:34
     * @Params：
     * @Return：
     */
    public List<Map<String, Object>> getGoodsCoupon(String goodsId, String customerId, CouponCustomerInfo couponCustomerInfo) {
        if (StringUtils.isEmpty(goodsId)) {
            throw GlobalException.build("商品ID不能为空");
        }
        List<Map<String, Object>> goodsCouponMapList = this.couponH5Dao.getCouponListByGoodsId(goodsId, couponCustomerInfo.getOrgId(), customerId);
        if (goodsCouponMapList == null || goodsCouponMapList.size() == 0) {
            return new ArrayList<>();
        }
        //组装所有商品关联的优惠券ID
        List<String> couponIds = new ArrayList<>();
        for (Map<String, Object> map : goodsCouponMapList) {
            //判断该优惠券的规则是否等于2 （指定商品不可用），如果是指定商品不可用那么需要判断里面是否包含了该商品
            //这里不用数据库比对的原因是因为goodsid是一个number，可能里面存在相同的任意ID，比如123，用like 或者find_in_set  1,2,3 12等都能找到。
            if (map.get("goodsType").toString().equals("2")) {
                String[] ids = map.get("goodsIds").toString().split(",");
                boolean isExit = false;
                for (String id : ids) {
                    if (id.equals(goodsId)) {
                        isExit = true;
                    }
                }
                if (!isExit) {
                    couponIds.add(map.get("couponId").toString());
                }
            } else {
                couponIds.add(map.get("couponId").toString());
            }
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("couponIds", couponIds);
        //useScene=-2表示线上线下混合使用+线上使用
        paramMap.put("useScene", -2);
        //请求获取所有的优惠券列表
        Object result = couponRequest.doRequest("customer-goods-coupon", paramMap, couponCustomerInfo);
        List<Map<String, Object>> goodsCouponList = (List<Map<String, Object>>) result;
        if (goodsCouponList == null || goodsCouponList.size() == 0) {
            return new ArrayList<>();
        }

        List<Map<String, Object>> couponList = new ArrayList<>();
        //遍历所有的设置项，判断是否可领取
        for (Map<String, Object> goodsCoupon : goodsCouponList) {
            Map<String, Object> ruleMap = null;
            List<Map<String, Object>> cList = goodsCouponMapList.stream().filter(map -> map.get("couponId").toString().equals(goodsCoupon.get("couponId").toString())).collect(Collectors.toList());
            if (cList != null && cList.size() > 0) {
                ruleMap = cList.get(0);
            }
            if (ruleMap != null) {
                //每个人最多能领多少张 -1无限制
                Integer customerCouponNum = (Integer) ruleMap.get("customerCouponNum");
                Integer orderCount = this.couponH5Dao.getCustomerStoreOrderCount(couponCustomerInfo.getCustomerId(), goodsCoupon.get("createCustomerId").toString());
                switch ((Integer) ruleMap.get("customerType")) {
                    case 0:
                        if (customerCouponNum == -1 || (Integer) goodsCoupon.get("usableNum") < customerCouponNum) {
                            couponList.add(goodsCoupon);
                        }
                        break;
                    case 1:
                        //新用户没有下过订单切  不限制最大领取数量或者领取的数量小于设置的最大数量，则可以继续领取
                        if (orderCount == 0 && (customerCouponNum == -1 || (Integer) goodsCoupon.get("usableNum") < customerCouponNum)) {
                            couponList.add(goodsCoupon);
                        }
                        break;
                    case 2:
                        //没有下过订单切  不限制最大领取数量或者领取的数量小于设置的最大数量，则可以继续领取
                        if (orderCount > 0 && (customerCouponNum == -1 || (Integer) goodsCoupon.get("usableNum") < customerCouponNum)) {
                            couponList.add(goodsCoupon);
                        }
                        break;
                    case 3:
                        if (!StringUtils.isEmpty(ruleMap.get("groupId"))) {
                            Integer isExit = this.couponH5Dao.isCustomerExitGroup(customerId, ruleMap.get("groupId").toString());
                            if (isExit > 0) {
                                couponList.add(goodsCoupon);
                            }
                        }else{
                            couponList.add(goodsCoupon);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
        return couponList;
    }

    /**
     * @Description：过滤哪些是可以领用的
     * @DateTime：2020/9/22 10:40
     * @Params：
     * @Return：
     */
    public UnderwayPublishVo getPublish(Map<String, Object> params, CouponCustomerInfo couponCustomerInfo) {
        if (StringUtils.isEmpty(params.get("createCustomerId"))) {
            return UnderwayPublishVo.builder().build();
        }
        List<String> publishIds = this.couponH5Dao.customerMeetTactics(couponCustomerInfo.getCustomerId());
        if (publishIds == null || publishIds.size() == 0) {
            return UnderwayPublishVo.builder().couponVoList(new ArrayList<>()).build();
        }
        params.put("publishIds", publishIds);
        Object result = couponRequest.doRequest(params.get("active").toString(), params, couponCustomerInfo);
        JSONObject resultObject = JSONObject.parseObject(result.toString());
        UnderwayPublishVo underwayPublishVo = JSON.toJavaObject(resultObject, UnderwayPublishVo.class);
        if (underwayPublishVo != null) {
            List<GoodsCouponVo> resultList = new ArrayList<>();
            List<GoodsCouponVo> couponList = underwayPublishVo.getCouponVoList();
            if (couponList != null && couponList.size() > 0) {
                for (GoodsCouponVo goodsCouponVo : couponList) {
                    CouponTacticsPo couponTacticsPo = this.couponH5Dao.getCouponGoodsData(goodsCouponVo.getCouponId());
                    Integer orderCount = this.couponH5Dao.getCustomerStoreOrderCount(couponCustomerInfo.getCustomerId(), goodsCouponVo.getCreateCustomerId());
                    switch (couponTacticsPo.getCustomerType()) {
                        case 0:
                            if (couponTacticsPo.getCustomerCouponNum() == -1 || goodsCouponVo.getUsableNum() < couponTacticsPo.getCustomerCouponNum()) {
                                resultList.add(goodsCouponVo);
                            }
                            break;
                        case 1:
                            //新用户没有下过订单切  不限制最大领取数量或者领取的数量小于设置的最大数量，则可以继续领取
                            if (orderCount == 0 && (couponTacticsPo.getCustomerCouponNum() == -1 || goodsCouponVo.getUsableNum() < couponTacticsPo.getCustomerCouponNum())) {
                                resultList.add(goodsCouponVo);
                            }
                            break;
                        case 2:
                            //没有下过订单切  不限制最大领取数量或者领取的数量小于设置的最大数量，则可以继续领取
                            if (orderCount > 0 && (couponTacticsPo.getCustomerCouponNum() == -1 || goodsCouponVo.getUsableNum() < couponTacticsPo.getCustomerCouponNum())) {
                                resultList.add(goodsCouponVo);
                            }
                            break;
                        case 3:
                            //用户分群
                            if (!StringUtils.isEmpty(couponTacticsPo.getGroupId())) {
                                Integer isExit = this.couponH5Dao.isCustomerExitGroup(couponCustomerInfo.getCustomerId(), couponTacticsPo.getGroupId());
                                if (isExit > 0) {
                                    resultList.add(goodsCouponVo);
                                }
                            } else {
                                resultList.add(goodsCouponVo);
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            underwayPublishVo.setCouponVoList(resultList);
        }
        return underwayPublishVo;
    }

    /**
     * @Description：通过店铺ID获取用户可用的优惠券列表
     * @DateTime：2020/8/21 16:12
     * @Params：
     * @Return：
     */
    public List<CheckMerchantOrderPo> getUsableCouponList(List<CheckMerchantOrderPo> checkOrderList, CouponCustomerInfo couponCustomerInfo, Boolean isVip) {
        if (checkOrderList == null || checkOrderList.size() == 0) {
            throw GlobalException.build("确认订单商品不能为空");
        }
        //过滤哪些优惠券可用，哪些不可用
        for (CheckMerchantOrderPo checkMerchantOrderPo : checkOrderList) {
            //获取用户的优惠券列表
            List<CustomerCouponVo> customerCouponList = this.getCustomerCouponList(couponCustomerInfo, checkMerchantOrderPo.getMerchantCustomerId());
            //商品数据
            List<ShoppingCartGoodsPo> goodsList = checkMerchantOrderPo.getGoodsList();
            //遍历用户的优惠券列表，并判断哪些优惠券可以使用
            for (CustomerCouponVo couponInfo : customerCouponList) {
                //获取优惠券的策略设置
                List<CouponTacticsPo> tacticsList = this.couponH5Dao.getCouponTacticsByCouponId(couponInfo.getCouponId());
                //判断是否为空，为空则直接跳出
                if (tacticsList == null || tacticsList.size() == 0) {
                    continue;
                }
                //策略拿第一条就行
                CouponTacticsPo tacticsPo = tacticsList.get(0);
                //先设置优惠券不可用
                couponInfo.setIsEnable(false);
                List<String> goodsIds = new ArrayList<>();
                boolean effectiveDate = CalendarUtils.isEffectiveDates(new Date(), couponInfo.getUsableStartTime(), couponInfo.getUsableEndTime());
                //判断是否在可用时间范围
                if (effectiveDate) {
                    Long goodsTotalPrice = 0L;
                    switch (tacticsPo.getGoodsType()) {
                        //全部商品
                        case 0:
                            //最小使用不限制，订单总价大于最小使用限制
                            if (checkMerchantOrderPo.getOrderTotalPriceTemp() >= couponInfo.getMinUsePrice()) {
                                couponInfo.setIsEnable(true);
                                //全部商品可用
                                couponInfo.setGoodsIds(null);
                            }
                            break;
                        //指定商品可用
                        case 1:
                            //这个优惠券的策略是某些商品可用
                            for (ShoppingCartGoodsPo goodsInfo : goodsList) {
                                for (CouponTacticsPo couponTacticsPo : tacticsList) {
                                    if (goodsInfo.getGoodsId().equals(couponTacticsPo.getGoodsId())) {
                                        goodsIds.add(goodsInfo.getGoodsId().toString());
                                        //判断是vip用vip价格
                                        if (isVip) {
                                            goodsTotalPrice += (goodsInfo.getMemberAmountCent() == 0 ? goodsInfo.getAmountCent() : goodsInfo.getMemberAmountCent()) * goodsInfo.getBuyCount();
                                        } else {
                                            goodsTotalPrice += new Double(goodsInfo.getAmountCent() * goodsInfo.getBuyCount()).longValue();
                                        }
                                        break;
                                    }
                                }
                            }
                            couponInfo.setGoodsIds(goodsIds);
                            //如果商品价格是0元，代表未找到关联商品
                            if (goodsTotalPrice == 0L) {
                                couponInfo.setCondition("商品不适用");
                            } else {
                                //商品金额大于最小可用金额
                                if (goodsTotalPrice >= couponInfo.getMinUsePrice()) {
                                    couponInfo.setIsEnable(true);
                                } else {
                                    couponInfo.setCondition("适用商品不满" + couponInfo.getMinUsePriceStr());
                                }
                            }
                            break;
                        //指定商品不可用
                        case 2:
                            //这个优惠券的策略是某些商品不可用
                            boolean isExit = false;
                            for (ShoppingCartGoodsPo goodsInfo : goodsList) {
                                for (CouponTacticsPo couponTacticsPo : tacticsList) {
                                    if (goodsInfo.getGoodsId().equals(couponTacticsPo.getGoodsId())) {
                                        isExit = true;
                                        break;
                                    }
                                }
                                //如果是在不可用的设置中不存在，代表商品可用
                                if (!isExit) {
                                    goodsIds.add(goodsInfo.getGoodsId().toString());
                                    if (isVip) {
                                        goodsTotalPrice += (goodsInfo.getMemberAmountCent() == 0 ? goodsInfo.getAmountCent() : goodsInfo.getMemberAmountCent()) * goodsInfo.getBuyCount();
                                    } else {
                                        goodsTotalPrice += new Double(goodsInfo.getAmountCent() * goodsInfo.getBuyCount()).longValue();
                                    }
                                }
                            }
                            if (goodsIds.size() == 0) {
                                couponInfo.setCondition("商品不适用");
                            } else {
                                //商品金额大于最小可用金额
                                if (goodsTotalPrice >= couponInfo.getMinUsePrice()) {
                                    couponInfo.setIsEnable(true);
                                } else {
                                    couponInfo.setCondition("适用商品不满" + couponInfo.getMinUsePriceStr());
                                }
                            }
                            //这个优惠券哪些商品可用
                            couponInfo.setGoodsIds(goodsIds);
                            break;
                        default:
                            break;
                    }
                } else {
                    couponInfo.setCondition("不在可用时间内");
                }
                couponInfo.setChecked(false);
            }
            checkMerchantOrderPo.setCustomerCouponList(customerCouponList);
        }
        return checkOrderList;
    }

    /**
     * @Description：获取用户的优惠券
     * @DateTime：2020/10/13 16:23
     * @Params：
     * @Return：
     */
    private List<CustomerCouponVo> getCustomerCouponList(CouponCustomerInfo couponCustomerInfo, String merchantCustomerId) {
        Map<String, Object> params = new HashMap<>();
        List<String> merchantCustomerIds = new ArrayList<>();
        merchantCustomerIds.add(merchantCustomerId);

        //获取该用户，确认订单所有店铺下的所有可用优惠券列表
        params.put("createCustomerIds", merchantCustomerIds);
        Object result = couponRequest.doRequest("usable-coupon-list", params, couponCustomerInfo);
        JSONArray resultJsonArray = JSONArray.fromObject(result);
        List<CustomerCouponVo> customerCouponList = JSONArray.toList(resultJsonArray, new CustomerCouponVo(), new JsonConfig());
        return customerCouponList;
    }

    /**
     * @Description：通过优惠券ID获取商品列表
     * @DateTime：2020/8/21 16:12
     * @Params：
     * @Return：
     */
    public Object getGoodsListByCouponId(String id, String orgId, String creator, Integer pageIndex, Integer pageSize) {
        CouponTacticsPo couponInfo = couponH5Dao.getCouponGoodsData(id);
        if (couponInfo == null || couponInfo.getGoodsType() == null) {
            throw GlobalException.build("该卡券已失效！");
        }
        Map params = new HashMap();
        params.put("id", id);
        params.put("goodsType", couponInfo.getGoodsType());
        params.put("orgId", orgId);
        if (!orgId.equals(creator)) {
            params.put("creator", creator);
        }
        //获取商品列表
        PageHelper.startPage(pageIndex, pageSize);
        List<MallGoodsPo> goodsList = couponH5Dao.getMerchantGoodsList(params);
        return new PageInfo(goodsList);
    }

    /**
     * @Description：核销优惠券
     * @DateTime：2020/12/3 15:27
     * @Params：
     * @Return：
     */
    public void useCustomerCoupon(String consumptionId, Integer isYzjCoupon, CouponCustomerInfo couponCustomerInfo,String customerId,String orgId) {
        String belongId ="";
        if(customerId!=null){
            Map verificater = couponH5Dao.getPassVerificaterByCustomerId(customerId);
            if(verificater==null || verificater.size()==0){
                throw GlobalException.build("暂无权限");
            }else {
                 belongId = verificater.get("belongId").toString();
            }
        }

        //雅智捷的核销
        if (isYzjCoupon.equals(1)) {
            CustomerCouponVo customerCouponVo = couponCacheService.getYzjCouponByConsumptionId(consumptionId);
            if(customerCouponVo==null){
                throw GlobalException.build("卡券失效");
            }
            if(customerCouponVo.getStatus()!=null && customerCouponVo.getStatus()!=0){
                throw GlobalException.build("卡券已核销");
            }
            if(customerCouponVo.getUsableStartTime()!=null && customerCouponVo.getUsableEndTime()!=null){
                try{
                    String usableStartTimeStr =customerCouponVo.getUsableStartTime();
                    String usableStartEndStr =customerCouponVo.getUsableEndTime();
                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date sd1=df.parse(usableStartTimeStr);
                    Date sd2=df.parse(usableStartEndStr);
                    Date nowDate = new Date();
                    if(sd1.after(nowDate) || nowDate.after(sd2)){
                        throw GlobalException.build("核销卡券失败,该卡券不在有效期内");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw GlobalException.build("核销卡券失败,该卡券不在有效期内");
                }
            }
            Map<String, Object> info = BeanMapUtils.beanToMap(customerCouponVo);
            if(!StringUtils.isEmpty(belongId) && !belongId.equals(info.get("createCustomerId"))){
                throw GlobalException.build("暂无权限");
            }


            Map<String, Object> checkResult = this.yzjRequest.checkMemberCoupon(customerCouponVo.getMemberCode(), consumptionId);
            if (checkResult != null && (boolean) checkResult.get("exist") && (int) checkResult.get("status") == 1) {
                Map<String, Object> useResult = this.yzjRequest.useMemberCoupon(customerCouponVo.getMemberCode(), consumptionId);
                if (!(useResult != null && (boolean) useResult.get("success"))) {
                    throw GlobalException.build("核销卡券失败");
                }
            } else {
                throw GlobalException.build("核销卡券失败");
            }
            //清除缓存
            couponCacheService.deleteYzjCouponByConsumptionId(consumptionId);
            //插入数据
            if(info!=null){
                info.put("source",2);
                this.addVerificate(info,orgId,customerId);
            }

        } else {
            //获取优惠券详情（本地）
            Map<String, Object> params = new HashMap<>();
            params.put("consumptionId", consumptionId);
            Object result = couponRequest.doRequest("customer-coupon-info", params, couponCustomerInfo);
            Map<String, Object> info = (Map) result;
            if(!StringUtils.isEmpty(belongId) && !belongId.equals(info.get("createCustomerId"))){
                throw GlobalException.build("暂无权限");
            }
            Map<String, Object> param = new HashMap<>();
            param.put("consumptionId", consumptionId);
            param.put("status", 0);
            couponRequest.doRequest("customer-coupon-use", param, couponCustomerInfo);
            //插入数据
            if(info!=null){
                info.put("source",1);
                this.addVerificate(info,orgId,customerId);
            }
        }
    }

    /**
     * @Description：插入核销记录
     * @DateTime：2020/12/3 15:27
     * @Params：
     * @Return：
     */
    public void addVerificate(Map<String, Object> info,String orgId,String customerId){
        info.put("orgId",orgId);
        String phone = "";
        if(!StringUtils.isEmpty(info.get("customerId"))){
            String user = info.get("customerId").toString();
            phone = couponH5Dao.getPhoneByCustomerId(user);
        }
        info.put("phone",phone);
        info.put("phone",phone);
        if(StringUtils.isEmpty(customerId)){
            //pc核销
            info.put("verificateUserId",-1);
            info.put("verificateUserName","系统管理员");
        }else {
            //h5核销
            Map verificater = couponH5Dao.getVerificater(customerId);
            info.put("verificateUserId",verificater.get("verificateUserId"));
            info.put("verificateUserName",verificater.get("verificateUserName"));
        }
        couponH5Dao.addVerificate(info);
    }

    public void addVerificater(Map<String, Object> parms) {
        if(StringUtils.isEmpty(parms.get("customerId"))){
            throw GlobalException.build("未登录！");
        }
        String customerId = parms.get("customerId").toString();
        int count = couponH5Dao.getVerificaterCountByCustomerId(customerId);
        if(count>0){
            throw GlobalException.build("请勿重复申请！");
        }
        couponH5Dao.addVerificater(parms);
    }

    public void getVerificaterCountByCustomerId(String customerId){
        int count = couponH5Dao.getVerificaterCountByCustomerId(customerId);
        if(count>0){
            throw GlobalException.build("请勿重复申请！");
        }
    }

    public Map getVerificaterByCustomerId(String customerId,String belongId) {
        return couponH5Dao.getVerificaterByCustomerId(customerId,belongId);
    }

    public void updateVerificater(Map<String, Object> parms) {
        couponH5Dao.updateVerificater(parms);
    }

    public void deleteVerificater(Map<String, Object> params) {
        couponH5Dao.deleteVerificater(params);
    }

    public Map getPassVerificaterByCustomerId(String customerId) {
        return couponH5Dao.getPassVerificaterByCustomerId(customerId);
    }
}
